package com.wolfeyes.framework.springsecurity.handle;

import com.alibaba.fastjson.JSON;
import com.wolfeyes.common.constant.HttpStatusConstants;
import com.wolfeyes.common.response.ResponseResult;

import lombok.extern.slf4j.Slf4j;

import org.springframework.security.web.session.SessionInformationExpiredEvent;
import org.springframework.security.web.session.SessionInformationExpiredStrategy;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @description 会话失效(账号被挤下线)处理逻辑
 * @description 当账号异地登录导致被挤下线时也要返回给前端json格式的数据，
 * @description 比如提示"账号下线"、"您的账号在异地登录，是否是您自己操作"或者"您的账号在异地登录,可能由于密码泄露，建议修改密码"等。
 * @description 这时就要实现SessionInformationExpiredStrategy（会话信息过期策略）来自定义会话过期时的处理逻辑
 * @author yanyljava
 * @description 自定义的会话信息过期策略
 * @create 2021-10-24 09:34
 */
@Slf4j
@Component
public class CustomizeSessionInformationExpiredStrategy implements SessionInformationExpiredStrategy {
	
	/**
	 * @title 会话失效(账号被挤下线)处理逻辑
	 */
	@Override
	public void onExpiredSessionDetected(SessionInformationExpiredEvent sessionInformationExpiredEvent) throws IOException, ServletException {
		
		log.debug("自定义的会话信息过期策略处理器被调用 Start！");
		ResponseResult responseResult = ResponseResult.error(HttpStatusConstants.USER_ACCOUNT_USE_BY_OTHERS, "账号被迫下线，请联系管理员!");
		HttpServletResponse httpServletResponse = sessionInformationExpiredEvent.getResponse();
		httpServletResponse.setContentType("text/json;charset=utf-8");
		httpServletResponse.getWriter().write(JSON.toJSONString(responseResult));
		log.debug("自定义的会话信息过期策略处理器被调用 End！");
	}
	
}
